<template>
  <div class="main">
    <div class="chat-header" @click="goBack()">
      <i class="el-icon-arrow-left"></i>
      返回
    </div>
    <div class="header">
      <el-input
          placeholder="搜索好友"
          v-model="keyWord">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <div class="font">搜索</div>
    </div>
    <div class="body" @scroll="handleScroll">
      <div class="card" v-for="(friend,index) in $store.state.friendStore.friends" :key="index"
           :class="{ 'last-item': index === chatStore.chats.length - 1 }"
      >
        <!--        @click="handleActiveItem(item,index)"-->
        <!--        <van-image class="avatar" round :src="logo"/>-->
        <!--        <div class="des">-->
        <!--          <div>{{ item.showName }}</div>-->
        <!--          <div>{{ item.lastContent }}</div>-->
        <!--        </div>-->
        <!--        <div class="count" v-if="item.unreadCount>0">{{ item.unreadCount }}</div>-->
        <friend-item v-show="friend.nickName.startsWith(keyWord)" :friend="friend" :index="index"
                     @del="handleDelItem(friend,index)" @click.native="handleActiveItem(friend,index)">
          <!--          :active="index === $store.state.friendStore.activeIndex"-->
        </friend-item>
      </div>
      <div class="card-zero" v-if="$store.state.friendStore.friends.length<=0">
        <div style="text-align: center">暂无数据</div>
      </div>
    </div>
  </div>
</template>

<script>
import httpRequest from "@/api/httpRequest";
import chatStore from "@/store/modules/chatStore";
import friendItem from "@/views/chat/component/FriendItem";

export default {
  name: "customer_consulation_friends",
  components: {
    friendItem
  },
  data() {
    return {
      type: '',
      keyWord: '',
      logo: require("@/assets/logo.png"),
      userList: [],
      dealerId: '',
      permissions: [],
      accountCode: '',
      userInfo: {}
    }
  },
  mounted() {
    this.$store.commit('setChildrenFlag', 0);
    this.accountCode = this.$route.query.accountCode
    //==========================================新逻辑
    let childrenFlag = this.$store.state.chatStore.childrenFlag
    if (childrenFlag != 1 && childrenFlag == 0) {
      this.first()
    }
  },
  computed: {
    chatStore() {
      return this.$store.state.chatStore
    }
  },
  methods: {
    handleScroll() {
    },
    first() {
      this.$store.dispatch('loginChat', this.$store.state.userInfo).then((data) => {
        console.log('子系统登录成功', data)
        // this.setCookie('username', this.$store.state.userInfo.userName) //主系统的userName
        // this.setCookie('password', '123456')
        this.$store.commit('setChildrenFlag', 1);
        sessionStorage.setItem("accessToken", data.accessToken);
        sessionStorage.setItem("refreshToken", data.refreshToken);
        // this.$message.success("登陆成功");
        httpRequest({
          url: "/user/self",
          methods: 'get'
        }).then((userInfo) => {
          this.init(userInfo);
        })
      })
    },
    loadUserInfo(friend, index) {
      return new Promise((resolve, reject) => {
        httpRequest({
          url: `/user/find/${friend.id}`,
          method: 'get'
        }).then((user) => {
          resolve(user)
          // 如果发现好友的头像和昵称改了，进行更新
          // if (user.headImageThumb != friend.headImage ||
          //     user.nickName != friend.nickName) {
          //   this.updateFriendInfo(friend, user, index)
          // }
        }).catch((error) => {
          reject(error)
        })
      })

    },
    async init(userInfo) {
      console.log('子系统的用户信息', userInfo)
      this.$store.commit("setUserInfo", userInfo);
      this.$store.commit("setUserState", this.$enums.USER_STATE.FREE);
      this.$store.commit("initStore");
      // if (this.friendStore.activeIndex >= 0) {
      //   let friend = this.friendStore.friends[this.friendStore.activeIndex];
      //  this.userInfo =await this.loadUserInfo(friend, this.friendStore.activeIndex);
      // }
      // this.$wsApi.createWebSocket('wss://debug.yasee.com.cn:8878/im', userInfo.id); //初始化websocket链接
      this.$wsApi.createWebSocket('wss://wechat.yasee.com.cn:8878/im', userInfo.id); //初始化websocket链接
      this.$wsApi.onopen(() => {
        // this.pullUnreadMessage();
      });
      this.$wsApi.onmessage((cmd, msgInfo) => {
        if (cmd == 2) {
          // 异地登录，强制下线
          this.$store.commit('setChildrenFlag', 0);
          // this.$message.error("您已在其他地方登陆，将被强制下线");
          // setTimeout(() => {
          //   location.href = "/";
          // }, 1000)
        } else if (cmd == 3) {
          // 插入私聊消息
          this.handlePrivateMessage(msgInfo);
        }
        // else if (cmd == 4) {
        //   // 插入群聊消息
        //   this.handleGroupMessage(msgInfo);
        // }
      })
    },
    pullUnreadMessage() {
      // 拉取未读私聊消息
      httpRequest({
        url: "/message/private/pullUnreadMessage",
        method: 'post'
      });
      // 拉取未读群聊消息
      httpRequest({
        url: "/message/group/pullUnreadMessage",
        method: 'post'
      });
    },
    handleDelItem(friend, index) {
      this.$confirm(`确认要解除与 '${friend.nickName}'的好友关系吗?`, '确认解除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        httpRequest({
          url: `/friend/delete/${friend.id}`,
          method: 'delete'
        }).then((data) => {
          this.$message.success("删除好友成功");
          this.$store.commit("removeFriend", index);
          this.$store.commit("removePrivateChat", friend.id);
        })
      })
    },
    handlePrivateMessage(msg) {
      // 好友列表存在好友信息，直接插入私聊消息
      let friend = this.$store.state.friendStore.friends.find((f) => f.id == msg.sendId);
      // let friend = chatStore.state.chats.find((f) => f.id == msg.sendId)
      if (friend) {
        this.insertPrivateMessage(friend, msg);
        // return;
      }
      // 好友列表不存在好友信息，则发请求获取好友信息
      // httpRequest({
      //   url: `/friend/find/${msg.sendId}`,
      //   method: 'get'
      // }).then((friend) => {
      //   this.insertPrivateMessage(friend, msg);
      //   this.$store.commit("addFriend", friend);
      // })
    },
    insertPrivateMessage(friend, msg) {
      console.log('处理私人消息')
      // let chatInfo = {
      //   type: 'PRIVATE',
      //   targetId: friend.id,
      //   showName: friend.nickName,
      //   headImage: friend.headImage
      // };
      // 打开会话
      // this.$store.commit("openChat", chatInfo);
      // 插入消息
      this.$store.commit("insertMessage", msg);
      this.$forceUpdate()
      console.log('强制刷新私人消息')
      // 播放提示音
      // this.playAudioTip();
    },
    playAudioTip() {
      let audio = new Audio();
      let url = require(`@/assets/audio/tip.wav`);
      audio.src = url;
      audio.play();
    },
    goBack() {
      this.$router.go(-1)
    },
    // search() {
    //   if (this.type == 'khjlzx') {
    //     this.getDataList()
    //   } else {
    //     this.getUserList()
    //   }
    // },
    // 获取参数
    // getParam(name) {
    //   if (window.location.search.indexOf("?") != -1) {
    //     const query =
    //         window.location.search.split("?")[1] +
    //         "&" +
    //         window.location.hash.split("?")[1];
    //     const vars = query.split("&");
    //     for (var i = 0; i < vars.length; i++) {
    //       var pair = vars[i].split("=");
    //       if (pair[0] == name) {
    //         return pair[1];
    //       }
    //     }
    //   } else {
    //     return "";
    //   }
    // },
    // 获取用户对应的客户经理
    // getUserList() {
    //   getManageList(
    //       {
    //         wxOpenid: this.openId,
    //         dealerName: this.keyWord
    //       }
    //   )
    //       .then((r) => {
    //         this.userList = r.data
    //       })
    //       .catch((e) => {
    //       });
    // },
    //获取众测和常规客户经理对应的用户列表
    // getDataList() {
    //   let query = {
    //     dealerId: this.dealerId,
    //     userName: this.keyWord
    //   }
    //   getUserList(query).then((res) => {
    //     this.userList = res.data
    //     // if (this.type == 'zc') {
    //     //   //拿到的众测用户unshift this.userList
    //     // } else if (this.type == 'cg') {
    //     //   //拿到常规用户 unshift进去
    //     // }
    //   })
    // },
    // gotoChat(item) {
    //   //下面逻辑是区分在店员服务和用户列表这两个页面去进行跳转的参数的区分
    //   let params = {}
    //   if (this.type == 'khjlzx') {
    //     params = {
    //       dealerId: item.dealerId,
    //       userId: item.userId,
    //       userName: item.userName,
    //       type: this.type
    //     }
    //   } else {
    //     params = {
    //       dealerId: item.dealerId,
    //       userId: item.userId,
    //       userName: item.dealerName,
    //       accountCode: this.accountCode
    //     }
    //   }
    //   this.$router.push({
    //     path: '/chat',
    //     query: params,
    //   })
    // }
    async handleActiveItem(friend, index) {
      // this.$store.commit("activeFriend", index,);
      this.$store.commit("activeChat", index,);
      // this.userInfo = await this.loadUserInfo(friend, index);
      let chat = {
        targetId: friend.id,
        showName: friend.nickName,
      }
      this.$router.push({path: '/chat', query: {chat: chat, accountCode: this.accountCode}})
      // this.$store.commit('activeMessage', newRecords)
    },
    // handleActiveItem(friend, index) {
    //   this.$store.commit("activeFriend", index);
    //   this.loadUserInfo(friend,index);
    // },
  },
}
</script>

<style scoped lang="less">
.main {
  width: 100%;

  .chat-header {
    font-size: 15px;
    padding: 10px;
    height: 20px;
    line-height: 20px;
    border-top: 1px solid #f0f0f0;
    background: #1989fa;
    color: #ffffff;
  }

  .header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 10px;

    .font {
      width: 50px;
      font-size: 15px;
      padding-left: 10px;
      color: #409EFF;
    }
  }

  .body {
    .last-item {
      border-bottom: 1px solid #f0f0f0; /* 替换为您想要的底部边框样式 */
    }

    .card-zero {
      margin-top: 10px;
      font-size: 15px;
      padding: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .card {
      //margin-top: 10px;
      font-size: 15px;
      padding: 15px;
      border-top: 1px solid #f0f0f0;

      display: flex;
      align-items: center;
      justify-content: flex-start;

      .avatar {
        width: 50px;
        height: 50px;
      }

      .des {
        margin-left: 10px;

        :nth-child(2) {
          margin-top: 10px;
          width: 200px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }

      .count {
        margin-left: auto;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: red;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
      }

    }
  }
}
</style>
